 Component({
   // 页面持有的数据

   data: {
     triggered: false, // 是否在下拉刷新中
     openhint: false, // 是否开启上拉刷新的结果提示，只有刷新失败或者数据加载结束才会开启
     hint: '', // 上拉刷新结果提示文字
     isReachBottom: false, //是否触底，控制loading显示
     timemove: undefined,
     time: undefined,
     fcolor: "green",
     opacity_data: 0.8,
     interval: undefined,
     pwidth: 0,
     pheight: 0,
     // todo-list数据
     items: {
       "3": {
         id: "3",
         content: "OS课设大作业",
         checked: false,
       },
       "2": {
         id: "2",
         content: "CV第四次实验作业",
         checked: false,
       },
       "1": {
         id: "1",
         content: "数据库大作业",
         checked: false,
       },
     },
     isItemsEmpty: true,
     // 输入框当前内容
     inputedValue: "",
     hitokoto: {
       "author": "QAQ",
       "content": "网络失败！请重试！",
     },
   },
   lifetimes: {
     // 在组件实例进入页面节点树时执行
     attached: function () {
       this.login(() => {
         const access = wx.getStorageSync("access");
         //从后端获取数据
         wx.request({
           //  url: "http://127.0.0.1:8000/api/weixin/data/",
           //  url: "http://www.todolist.com/api/weixin/data/",
           url: "http://192.168.43.250:8000/api/weixin/data/",
           header: {
             Authorization: "Bearer " + access,
           },
           success: (res) => {
             wx.showToast({
               title: '数据获取成功！',
               duration: 1500
             });
             console.log(res);
             this.setData({
               items: res.data.items.filter((v) => v.checked === false),
             });
           },
         });
       });

     },
     detached: function () {
       console.log(this.data.interval);
       clearInterval(this.data.interval);
     }
   },
   pageLifetimes: {
     show: function () {
       //加载一言
       this.updateHitokoto();

       let that = this;
       //获取系统信息
       wx.getSystemInfo({
         //获取系统信息成功，将系统窗口的宽高赋给页面的宽高
         success: function (res) {
           that.setData({
             pwidth: res.windowWidth,
             pheight: res.windowHeight

           })

         }
       });
       //加入时钟
       this.canvasClock(this.data.pwidth, this.data.pheight);
       //对canvasAPP函数循环调用
       let interval = setInterval(this.canvasClock, 1000, this.data.pwidth, this.data.pheight);
       this.setData({
         interval: interval
       })
       //console.log(this.interval);
     },
     hide: function () {
       console.log("hide");
     }
   },
   methods: {
     shuaxin: function () {
       this.onLoad()
     },
     copy_text: function (e) {
       var that = this;
       console.log(e);
       wx.setClipboardData({
         data: that.data.OrderModel.OrderNo,
         success: function (res) {
           wx.showToast({
             title: '复制成功',
             duration: 800
           });
         }
       });
     },
     canvasClock: function (width, height) {
       var context = wx.createContext() //创建并返回绘图上下文（获取画笔）
       context.setStrokeStyle('purple');
       context.setGlobalAlpha(0.2);
       //设置宽高
       // console.log(width)
       // console.log(height)
       var R = width / 2 - 55; //设置文字距离时钟中心点距离
       //重置画布函数
       function reSet() {
         context.height = context.height; //每次清除画布，然后变化后的时间补上
         context.translate(width / 2, height / 2); //设置坐标轴原点
         context.save(); //保存中点坐标1
       }
       //绘制中心圆和外面大圆
       function circle() {
         //外面大圆
         context.setLineWidth(2);
         context.beginPath();
         context.arc(0, 0, width / 2 - 30, 0, 2 * Math.PI, true);
         context.closePath();
         context.stroke();
         //中心圆
         context.beginPath();
         context.arc(0, 0, 8, 0, 2 * Math.PI, true);
         context.closePath();
         context.stroke();
       }
       //绘制小格
       function smallGrid() {
         context.setLineWidth(1);
         context.rotate(-Math.PI / 2); //时间从3点开始，倒转90度
         for (var i = 0; i < 60; i++) {
           context.beginPath();
           context.rotate(Math.PI / 30);
           context.moveTo(width / 2 - 30, 0);
           context.lineTo(width / 2 - 40, 0);
           context.stroke();
         }
       }
       //绘制大格
       function bigGrid() {
         context.setLineWidth(5);
         for (var i = 0; i < 12; i++) {
           context.beginPath();
           context.rotate(Math.PI / 6);
           context.moveTo(width / 2 - 30, 0);
           context.lineTo(width / 2 - 45, 0);
           context.stroke();
         }
       }
       //指针运动函数
       function move() {
         var t = new Date(); //获取当前时间
         var h = t.getHours(); //获取小时
         h = h > 12 ? (h - 12) : h; //将24小时制转化为12小时制
         var m = t.getMinutes(); //获取分针
         var s = t.getSeconds(); //获取秒针
         context.save(); //再次保存2
         context.setLineWidth(7);
         //旋转角度=30度*（h+m/60+s/3600）
         //分针旋转角度=6度*（m+s/60）
         //秒针旋转角度=6度*s
         context.beginPath();
         //绘制时针
         context.rotate((Math.PI / 6) * (h + m / 60 + s / 3600));
         context.moveTo(-20, 0);
         context.lineTo(width / 4.5 - 20, 0);
         context.stroke();
         context.restore(); //恢复到2,（最初未旋转状态）避免旋转叠加
         context.save(); //3
         //画分针
         context.setLineWidth(5);
         context.beginPath();
         context.rotate((Math.PI / 30) * (m + s / 60));
         context.moveTo(-20, 0);
         context.lineTo(width / 3.5 - 20, 0);
         context.stroke();
         context.restore(); //恢复到3，（最初未旋转状态）避免旋转叠加
         context.save();
         //绘制秒针
         context.setLineWidth(2);
         context.beginPath();
         context.rotate((Math.PI / 30) * s);
         context.moveTo(-20, 0);
         context.lineTo(width / 3 - 20, 0);
         context.stroke();
       }
       function drawClock() {
         reSet();
         circle();
         smallGrid();
         bigGrid();
         move();
       }
       drawClock() //调用运动函数
       // 调用 wx.drawCanvas，通过 canvasId 指定在哪张画布上绘制，通过 actions 指定绘制行为
       wx.drawCanvas({
         canvasId: 'myCanvas',
         actions: context.getActions()
       })
     },
     uploadDate: function (items) {
       const access = wx.getStorageSync("access");
       wx.request({

         //  url: "http://127.0.0.1:8000/api/weixin/data/",
         //url: "http://www.todolist.com/api/weixin/data/",
         url: "http://192.168.43.250:8000/api/weixin/data/",
         method: "POST",
         header: {
           Authorization: "Bearer " + access,
         },
         data: {
           items: items,
         },
         success: function () {
           wx.showToast({
             title: '更新成功！',
             duration: 500
           })
         },
         fail: function () {
           wx.showToast({
             title: '添加失败！请重试！',
             duration: 1500
           })
         }
       });
     },
     login: function (callback = (() => {})) {
       if (!this.isTokenAvailable()) {
         console.log("Get Token from dj.");
         //获取token文件并传入callback
         this.getToken(callback);
       } else {
         console.log("Get Token from storage");
         //如果缓存中token未过期则执行callback
         callback();
       }
     },
     //callback本身是一个函数
     getToken: function (callback = (() => {})) {
       wx.login({
         // 获取code
         success(res) {
           console.log("get code");
           if (res.code) {
             // 用code换取token
             wx.request({
               //url: "http://127.0.0.1:8000/api/weixin/login/",
               //url: "http://www.todolist.com/api/weixin/login/",
               url: "http://192.168.43.250:8000/api/weixin/login/",
               method: "POST",
               data: {
                 code: res.code,
               },
               success: (res) => {
                 // 在小程序调试器中查看是否收到token
                 console.log(res);
                 const access = res.data.access;
                 // 将token保存到缓存
                 wx.setStorage({
                   key: "access",
                   data: access
                 });
                 // 保存token的获取时间
                 wx.setStorage({
                   key: "access_time",
                   data: Date.parse(new Date()),
                 });
                 //用token获取用户数据
                 wx.request({
                   //  url: "http://127.0.0.1:8000/api/weixin/data/",
                   //url: "http://www.todolist.com/api/weixin/data/",
                   url: "http://192.168.43.250:8000/api/weixin/data/",
                   header: {
                     // 注意字符串 'Bearer ' 尾部有个空格！
                     Authorization: "Bearer " + access,
                   },
                   success: (res) => {
                     // 在小程序调试器中查看返回值是否正确
                     console.log(res);
                     callback(); //以便在登录完成后执行后续动作
                   },
                 });
               },
             });
           } else {
             console.log("登录失败！" + res.errMsg);
           }
         },
       });
     },
     // 返回布尔值，检查token是否过期
     isTokenAvailable: function () {
       const now = Date.parse(new Date());
       try {
         const accessTime = wx.getStorageSync("access_time");
         if (accessTime !== "" && now - accessTime < 5 * 60 * 1000) {
           return true;
         }
       } catch {
         console.log("获取Token失败！");
       }
       return false;
     },
     // 监听键盘输入事件
     keyInput: function (e) {
       this.setData({
         inputedValue: e.detail.value,
       });
     },
     // 监听提交按钮
     inputSubmit: function () {
       let value = this.data.inputedValue;
       if (value.replace(/\s+/g, '').length == 0) {
         wx.showToast({
           title: '输入不为空！',
           icon: "error",
           duration: 1000
         });
         return;
       }
       wx.showLoading({
         title: '正在添加待办...',
       })
       if (this.data.time) {
         clearInterval(this.data.time);
       }
       this.setData({
         opacity_data: 0.99
       })
       let that = this;
       let t = setInterval(function () {
         let opc = that.data.opacity_data * 0.985;
         //console.log(opc);
         if (opc <= 0.8) {
           clearInterval(that.data.time);
           opc = 0.8;
         }
         that.setData({
           opacity_data: opc
         })
       }, 50);
       this.setData({
         time: t
       })
       this.login(() => {
         this._inputSubmit();

       });
     },
     _inputSubmit: function () {

       let items = JSON.parse(JSON.stringify(this.data.items));
       // 设置新条目的id
       let newID = 1;
       if (items[0] !== undefined) {
         newID = items[0].id + 1;
       }
       // 将新条目更新到items中
       // 并将输入框的值清空
       items.unshift({
         id: newID,
         content: this.data.inputedValue,
         checked: false,
       });
       this.setData({
         items: items,
         inputedValue: "",
       });
       wx.setStorage({
         key: "items",
         data: items,
       });
       this.uploadDate(items); //将items提交到django
       setTimeout(() => {
         wx.hideLoading()
       }, 1100)

     },
     checkboxChange: function (e) {
       this.login(() => {
         this._checkboxChange(e);
       });
     },
     // 监听多选框的状态改变事件
     _checkboxChange: function (e) {
       // 页面持有的数据
       // 获取本地数据的写法为 this.data.xxx
       const items = JSON.parse(JSON.stringify(this.data.items));
       // checkbox持有的数据
       const values = e.detail.value;
       // 将items和values进行对比
       // 根据values的值更新页面数据(即data.items)
       for (let i = 0, lenI = items.length; i < lenI; ++i) {
         items[i].checked = false;
         for (let j = 0, lenJ = values.length; j < lenJ; ++j) {
           // values[j]是String
           // 将其转换为Int
           if (items[i].id === parseInt(values[j])) {
             items[i].checked = true;
             break;
           }
         }
       }
       // 更新数据
       this.setData({
         items: items,
       });

       // 打印的内容会展现在调试器中
       console.log(this.data.items);

       wx.setStorage({
         key: "items",
         data: items,
       });
       this.uploadDate(items); //将items提交到django
     },
     updateHitokoto: function (e) {
       this.login(() => {
         this._updateHitokoto(e);
       });
     },
     _updateHitokoto: function (e) {
       const access = wx.getStorageSync("access");
       let that = this;
       let choice = "hao";
       let msg = "加油！坚持下去！";

       if (e) {
         console.log(e.currentTarget.dataset.choice);
         choice = e.currentTarget.dataset.choice;
         this.setData({
           fcolor: e.currentTarget.dataset.fcolor
         })
       }
       if (choice == "du") {
         msg = "笑一笑就过去啦~";
       }
       wx.request({
         //  url: "http://127.0.0.1:8000/api/weixin/jitang/",
         //  url: "http://www.todolist.com/api/weixin/jitang/",

         url: "http://192.168.43.250:8000/api/weixin/jitang/",
         method: "POST",
         header: {
           Authorization: "Bearer " + access,
         },
         data: {
           choice: choice,
         },
         success: function (res) {
           console.log(res)
           const hitokoto = res.data;
           // 将hitokoto保存
           that.setData({
             hitokoto: {
               author: hitokoto.data.author,
               content: hitokoto.data.content
             }

           });
           wx.showToast({
             title: msg,
             duration: 1200
           });
         },
         fail: function () {
           wx.showToast({
             title: "人生难免有挫折~",
             duration: 1200
           });
         }
       });
     },
     opacitystart: function () {
       this.setData({
         opacity_data: 0.95
       })
     },
     opacitymove: function () {
       this.setData({
         opacity_data: 1
       })
     },
     opacityend: function () {
       //  this.setData({
       //    opacity_data: 0.35
       //  })
       if (this.data.timemove) {
         clearInterval(this.data.timemove);
       }
       this.setData({
         opacity_data: 0.95
       })
       let that = this;

       let t = setInterval(function () {
         let opc = that.data.opacity_data * 0.985;
         //console.log(opc);
         if (opc <= 0.8) {
           clearInterval(that.data.timemove);
           opc = 0.8;
         }
         that.setData({
           opacity_data: opc
         })
       }, 50);
       this.setData({
         timemove: t
       })
     },
     //上拉刷新
     onRefresh() {
       setTimeout(() => {
         this.setData({
           triggered: false,
         });
         const access = wx.getStorageSync("access");
         //从后端获取数据
         wx.request({
           //  url: "http://127.0.0.1:8000/api/weixin/data/",
           //  url: "http://www.todolist.com/api/weixin/data/",
           url: "http://192.168.43.250:8000/api/weixin/data/",
           header: {
             Authorization: "Bearer " + access,
           },
           success: (res) => {
             console.log(res);
             this.setData({
               items: res.data.items.filter((v) => v.checked === false),
             });
             wx.showToast({
               title: '刷新成功！',
               duration: 900
             })
           },
         });
       }, 1000)
     },
     scrollBottom() {
       this.getData()
     },
     getData() {
       this.setData({
         isReachBottom: true
       })
       // 模拟发出请求
       setTimeout(() => {
         this.setData({
           isReachBottom: false,
           openhint: true,
           hint: '已加载到最底部'
         })
       }, 2000)
     },
   },

 });